<template>
  <div class="page__feedback">
    <div class="page__feedback_body">
      <el-form
        ref="refForm"
        :model="form"
        size="large"
        :show-message="false"
        label-position="top"
        :rules="rules"
      >
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item
              label="您的操作系统是："
              props="system"
              class="label-left"
            >
              <el-input
                v-model="form.system"
                placeholder="请输入你的操作系统"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="当前使用的版本："
              props="system"
              class="label-left"
            >
              <el-input v-model="form.version" placeholder="输入你的版本" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          label="描述您的功能建议或错误问题:"
          props="system"
          :required="true"
        >
          <el-input
            v-model="form.content"
            type="textarea"
            placeholder="请输入您的功能建议，或所遇到问题的详细描述，我们将及时处理。"
            :rows="4"
            @blur="form.content=form.content.trim()"
          />
        </el-form-item>
        <el-form-item props="files">
          <template #label>
            <span>上传截图：</span>
            <em class="op-7">（最多支持三张图片，单张图片大小不超过5M）</em>
          </template>

          <el-upload
            v-model:file-list="form.files"
            :class="{ limit__lenght: form.files.length >= 3 }"
            :accept="imgFileAccept"
            :on-remove="handleRemove"
            :on-preview="handlePictureCardPreview"
            :before-upload="hdanleBeforeUpload"
            :http-request="handleUpload"
            list-type="picture-card"
          >
            <svg-icon icon-class="add-plus" class="fs30" />
          </el-upload>
        </el-form-item>
        <el-form-item label="联系方式:" props="connect" :required="true">
          <el-input
            v-model="form.connect"
            placeholder="建议留下你的QQ号或者微信号，方便我们及时与您联系"
            :style="{ width: '510px' }"
            @blur="form.connect=form.connect.trim()"
          />
        </el-form-item>
      </el-form>
      <div>
        <el-button
          type="primary"
          class="submit__btn"
          size="large"
          @click="handleSubmit"
        >
          提交
        </el-button>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :show-close="true" title="预览">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
        style="width: 100%"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="Feedback">
import PsMessage from "@/components/message/index";
import { reactive, ref, onMounted } from "vue";
import {
  type UploadInstance,
  type UploadRequestOptions,
  type UploadProps
} from "element-plus";
import { storeToRefs } from "pinia";
import { systemAppStore } from "@/stores/system";
import { feedback } from "@/api/common";
import { reportInfoApi } from "@/xz-fn";
// import { useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
// import UserQrCode from "@/components/user-qrcode/index.vue";
import { formatVersion } from "@/utils";
const refForm = ref<FormInstance>();
const system = systemAppStore();
// const route = useRoute();
const { appInfo, sysInfo } = storeToRefs(system);
const form = reactive({
  system: sysInfo.value.os_name,
  version: formatVersion(appInfo.value.version),
  content: "",
  files: [],
  connect: ""
});

const resetForm = () => {
  form.content = "";
  form.files = [];
  form.connect = "";
};
const imgFileTypes = ['gif', 'svg', 'png', 'jpeg', 'jpg', 'webp']
const imgFileAccept = ref(imgFileTypes.map(s => '.'+s).join(','))
const imgFileTypes2 = imgFileTypes.concat('svg+xml')
const imageFormatErr = `只能选择 ${imgFileTypes.join('、').replace(`、${imgFileTypes.slice(-1)[0]}`, ` 或 ${imgFileTypes.slice(-1)[0]}`)} 格式的图片`
const handleRemove = () => {};
const handleUpload = async (opt: UploadRequestOptions) => {};
const hdanleBeforeUpload: UploadInstance["beforeUpload"] = (file) => {
  if (form.files.length >= 3) {
    PsMessage("最多支持三张图片");
    return false;
  }
  const types = file.type.split('/')
  const format = types[0]
  const fileType = types[1]
  if(format !== 'image' || !imgFileTypes2.some(s => s === fileType )){
    PsMessage(imageFormatErr);
    return false;
  }

  if (file.size > 5 * 1024 * 1024) {
    PsMessage("单张图片大小不超过5M");
    return false;
  }
  return true;
};

const validateContent = (rule: any, value: any, callback: any) => {
  if (!value) {
    PsMessage("请输入描述内容");
    return callback(true);
  }

  return callback();
};
const validatorConnect = (rule: any, value: any, callback: any) => {
  if (!value) {
    PsMessage("请输入联系方式");
    return callback(true);
  }

  return callback();
};
const rules = reactive<FormRules<typeof form>>({
  content: [{ validator: validateContent, trigger: "blur" }],
  connect: [{ validator: validatorConnect, trigger: "blur" }]
});

const handleSubmit = async () => {
  if (!form.version || !/^\d+\.\d+\.\d+\.\d+$/.test(form.version)) {
    PsMessage("请输入正确格式的版本");
    return;
  }
  if (!form.content) {
    PsMessage("请输入描述内容");
    return;
  }
  if (!form.connect) {
    PsMessage("请输入联系方式");
    return;
  }
  const formdata = new FormData();
  formdata.append("come_from", "32769");
  formdata.append("os", form.system);
  formdata.append("version", form.version || appInfo.value.version);
  formdata.append("appid", appInfo.value.appID);
  formdata.append("pcid", appInfo.value.uuid);
  formdata.append("content", form.content);
  formdata.append("contact", form.connect);
  if (appInfo.value.channel) {
    formdata.append("union", appInfo.value.channel);
  }
  for (let i = 0; i < form.files.length; i++) {
    formdata.append("image", (form.files[i] as any).raw);
  }
  feedback(formdata)
    .then(() => {
      PsMessage("已收到您的反馈 我们将尽快优化");
      // handleClose()
      resetForm();
    })
};

const dialogVisible = ref(false);
const dialogImageUrl = ref("");
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
onMounted(() => {
  // if (route.query.from === "uninstall") {
  // }
});

reportInfoApi(66);
</script>

<style lang="scss" scoped>
$fill-color: rgba(78, 95, 255, 0.05);
.page__feedback {
  padding: 5px;
}
.page__feedback_body {
  overflow: auto;
  height: 100%;
  padding: 25px;
}
:deep(
    .el-upload-list__item.is-success:focus .el-upload-list__item-status-label
  ) {
  opacity: 1;
  display: inline-block;
}
:deep(.el-icon--close-tip) {
  display: none !important;
}
:deep(.el-form-item) {
  margin-bottom: 16px;
  &.label-left {
    display: flex;
    align-items: center;
    .el-form-item__label {
      margin: 0;
    }
  }
}
:deep(.el-form-item__label) {
  font-weight: bold;
  color: var(--el-text-color-primary);
}
:deep(.el-input),
:deep(.el-textarea) {
  // --el-input-border-color: rgba(var(--el-color-primary-rgb), 0.5);
  // --el-input-hover-border-color: rgba(var(--el-color-primary-rgb), 1);
  --el-input-text-color: var(--el-text-color-primary);
}
:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  background: rgba(var(--el-color-primary-rgb), 0.05);
}
:deep(.el-textarea__inner) {
  background: rgba(var(--el-color-primary-rgb), 0.05);
}
:deep(.el-upload-list__item) {
  width: 100px;
  height: 100px;
  outline: none;
}
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  // color: rgba(var(--el-color-primary-rgb), 0.8);
  // border: 1px solid rgba(var(--el-color-primary-rgb), 0.5);
  color: var(--el-text-color-secondary);
  border: 1px solid var(--el-border-color);
  background-color: rgba(var(--el-color-primary-rgb), 0.05);
  &:hover {
    color: rgba(var(--el-color-primary-rgb), 1);
    border-color: rgba(var(--el-color-primary-rgb), 1);
  }
}
.add__plus {
  width: 100px;
  height: 100px;
}
.submit__btn {
  width: 146px;
}
:deep(.limit__lenght .el-upload.el-upload--picture-card) {
  display: none;
}
</style>
